package com.dyzx.hbb.modules.wms.controller;


import cn.hutool.core.bean.BeanUtil;
import com.dyzx.hbb.common.base.Result;
import com.dyzx.hbb.common.config.MyLambdaQueryWrapper;
import com.dyzx.hbb.common.controller.BaseValidController;
import com.dyzx.hbb.common.utils.Utils;
import com.dyzx.hbb.modules.wms.entity.*;
import com.dyzx.hbb.modules.wms.query.WmsStockInOrdersQuery;
import com.dyzx.hbb.modules.wms.service.WmsInventoryService;
import com.dyzx.hbb.modules.wms.service.WmsProductService;
import com.dyzx.hbb.modules.wms.service.WmsStockInDetailsService;
import com.dyzx.hbb.modules.wms.service.WmsStockInOrdersService;
import com.dyzx.hbb.modules.wms.vo.WmsStockInDetailsVO;
import com.dyzx.hbb.modules.wms.vo.WmsStockInOrdersUVO;
import com.dyzx.hbb.modules.wms.vo.WmsStockInOrdersVO;
import com.dyzx.hbb.security.context.SecurityContextHolder;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * 入库单管理控制器
 * <p>处理仓库管理系统中入库单的创建、查询和相关业务逻辑
 * <p>主要职责：
 * <ul>
 * <li>提供入库单的创建接口</li>
 * <li>支持按条件查询入库单列表</li>
 * <li>处理入库单与商品明细的关联</li>
 * <li>实现库存数量的增加操作</li>
 * <li>管理入库单的状态和基础信息</li>
 * </ul>
 * <p>设计意图：为仓库管理模块提供标准化的入库流程管理，
 * 确保入库操作的准确性和可追踪性
 *
 * @author 开发团队
 * @version 1.0.0
 * @since 2023-05-30
 */
@Tag(name = "入库单管理", description = "入库单相关接口")
@RestController
@RequestMapping("/wms/stock/in/orders")
public class WmsStockInOrdersController extends BaseValidController<
        WmsStockInOrdersService,
        WmsStockInOrders,
        WmsStockInOrdersQuery,
        WmsStockInOrdersVO,
        WmsStockInOrdersUVO
        > {

    @Autowired
    private WmsStockInOrdersService service;

    @Autowired
    private WmsInventoryService inventoryService;

    @Autowired
    private WmsStockInDetailsService detailsService;
    @Autowired
    private WmsProductService productService;

    @Override
    protected WmsStockInOrdersService getBaseService() {
        return service;
    }

    @Override
    protected MyLambdaQueryWrapper<WmsStockInOrders> queryWrapper(WmsStockInOrdersQuery query) {
        MyLambdaQueryWrapper<WmsStockInOrders> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.select(WmsStockInOrders::getId)
                .select(WmsStockInOrders::getNo)
                .houseName(WmsStockInOrders::getHouseId).as("house_name")
                .select(WmsStockInOrders::getStatus)
                .select(WmsStockInOrders::getCreateDate)
                .select(WmsStockInOrders::getUpdateDate)
                .select(WmsStockInOrders::getOperatorId)
                .select(WmsStockInOrders::getPrice)
                .select(WmsStockInOrders::getQuantity);
        queryWrapper.orderByDesc(WmsStockInOrders::getCreateDate);

        if (query != null) {
            queryWrapper.likeRight(query.getNo() != null, WmsStockInOrders::getNo, query.getNo())
                    // .eq(query.getType() != null, WmsStockInOrders::getType, query.getType())
                  //  .eq(query.getStatus() > 0, WmsStockInOrders::getStatus, query.getStatus())
                    .eq(query.getHouse_id() != null, WmsStockInOrders::getHouseId, query.getHouse_id())
                    .eq(query.getLocation_id() != null, WmsStockInOrders::getLocationId, query.getLocation_id())
                    .ge(query.getLocationAreaId() != null, WmsStockInOrders::getLocationAreaId, query.getLocationAreaId());
        }
        return queryWrapper;
    }

    @Override
    protected MyLambdaQueryWrapper<WmsStockInOrders> queryInfoWrapper() {
        MyLambdaQueryWrapper<WmsStockInOrders> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.select(WmsStockInOrders::getId)
                .select(WmsStockInOrders::getNo)
                .houseName(WmsStockInOrders::getHouseId).as("house_name")
                .houseLeaderName(WmsStockInOrders::getHouseId).as("house_leader_name")
             //   .userName(WmsStockInOrders::getSalesmanId).as("salesman_name")
               // .userName(WmsStockInOrders::getAuditorId).as("auditor_name")
              //  .userName(WmsStockInOrders::getExporterId).as("exporter_name")
                .select(WmsStockInOrders::getStatus)
                .select(WmsStockInOrders::getCreateDate)
                .select(WmsStockInOrders::getUpdateDate)
                .select(WmsStockInOrders::getOperatorId)
                .select(WmsStockInOrders::getQuantity)
                .select(WmsStockInOrders::getPrice);

        queryWrapper.orderByDesc(WmsStockInOrders::getCreateDate);
        return queryWrapper;
    }

    @Override
    protected WmsStockInOrders addValid(WmsStockInOrdersVO entity) {
        return null;
    }

    @Override
    protected WmsStockInOrders editValid(WmsStockInOrdersUVO entity) {
        return null;
    }

    /**
     * 新增
     */
    @Operation(summary = "新增")
    @PostMapping
    public Result<Boolean> save(@Valid @RequestBody WmsStockInOrdersVO entity) {
        if (entity == null) {
            return Result.error("参数不能为空");
        }

        WmsStockInOrders entityCopy = new WmsStockInOrders();
        BeanUtil.copyProperties(entity, entityCopy);
        if (entityCopy == null) {
            return Result.error("创建实体对象失败");
        }

        List<WmsStockInDetailsVO> details = entity.getDetails();

 /*       Class<?> aClass = entityCopy.getClass();
        // 方案二：检查字段存在性（需要时使用）
        boolean hasOrganField = Arrays.stream(aClass.getDeclaredFields())
                .anyMatch(f -> ORGAN_FIELD.equals(f.getName()));
        boolean hasOperatorField = Arrays.stream(aClass.getDeclaredFields())
                .anyMatch(f -> OPRERATOR_FIELD.equals(f.getName()));
        Long userId = SecurityContextHolder.getUserId();
        if(hasOperatorField) {
            BeanUtil.setProperty(entityCopy, OPRERATOR_FIELD, userId);

        }

        if(hasOrganField){
            Long organId = SecurityContextHolder.getOrganId();
            BeanUtil.setProperty(entityCopy, ORGAN_FIELD, organId);

        }
*/
        Long userId = SecurityContextHolder.getUserId();
        entityCopy.setOperatorId(userId);
        Long organId = SecurityContextHolder.getOrganId();
        entityCopy.setOrganId(organId);
        String s = Utils.generateYyMMOrderNumber("IN");
        entityCopy.setNo(s);

        boolean save = getBaseService().save(entityCopy);
        if (save) {
            if (details != null && !details.isEmpty()) {
                List<WmsStockInDetails> wmsStockInDetails = new ArrayList<>();

                for (WmsStockInDetailsVO detail : details) {

                    WmsStockInDetails item = new WmsStockInDetails();

                    BeanUtil.copyProperties(detail, item);
                    item.setUniPrice((long) (detail.getAmt()));
                    item.setOrderId(entityCopy.getId());
                    item.setOperatorId(userId);
                    item.setOrganId(organId);
                    WmsInventory inventory = inventoryService.addInventory(item);
                    item.setInventoryId(inventory.getId());
                    //   WmsInventory inventory = inventoryService.getInventory(detail);
                    wmsStockInDetails.add(item);
                }
                boolean b = detailsService.saveBatch(wmsStockInDetails);
                if (b) {
                    //productId
                    List<Long> pIds = wmsStockInDetails.stream().map(WmsStockInDetails::getProductId).toList();
                    MyLambdaQueryWrapper<WmsProduct> queryWrapper = new MyLambdaQueryWrapper<>();
                    queryWrapper.in(WmsProduct::getId, pIds);
                    queryWrapper.isNull(WmsProduct::getAmt);
                    List<WmsProduct> products = productService.list(queryWrapper);
                    List<WmsProduct> productsIpdate = new ArrayList<>();
                    if (products != null && !products.isEmpty()) {
                        // uniPrice
                        for (WmsProduct product : products) {
                            Long uniPrice = wmsStockInDetails.stream().filter(d -> d.getProductId().equals(product.getId()))
                                    .map(WmsStockInDetails::getUniPrice).reduce(0L, Long::sum);
                            product.setAmt(uniPrice);
                            productsIpdate.add(product);
                        }
                        productService.updateBatchById(productsIpdate);
                    }

                    Long totalAmt = wmsStockInDetails.stream().map(WmsStockInDetails::getUniPrice).reduce(0L, Long::sum);

                    entityCopy.setPrice(totalAmt);
                    getBaseService().updateById(entityCopy);
                    return Result.ok();
                } else {
                    return Result.error("保存失败");
                }
            }
        }
        return save ? Result.ok() : Result.error("保存失败");
    }
}